package lj.courseinterect.dao;

import lj.courseinterect.dao.i.StudentDao;
import lj.courseinterect.dao.i.TeacherDao;
import lj.courseinterect.entity.Student;
import lj.courseinterect.entity.Teacher;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaTeacherDao extends JpaDao<Teacher, Long> implements TeacherDao{

    public JpaTeacherDao() {
        super(Teacher.class);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        Teacher tea = this.findByTeaNum(username);
//        if (null == tea) {
//            throw new UsernameNotFoundException("The teanum  " + username + " was not found");
//        }

        return tea;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Teacher findByTeaNum(String teaNum) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<Teacher> criteriaQuery = builder.createQuery(this.entityClass);

        Root<Teacher> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("teaNum");
        criteriaQuery.where(builder.equal(namePath, teaNum));

        TypedQuery<Teacher> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<Teacher> teachers = typedQuery.getResultList();

        if (teachers.isEmpty()) {
            return null;
        }

        return teachers.iterator().next();
    }


}
